<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="包名" value="1"></el-option>
              <el-option label="包名网址" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" min-width="130" align="center" prop="package_name" label="应用名称"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="160" align="center" prop="package" label="应用包名"> </el-table-column>
      <el-table-column v-if="colData[2].istrue" label="应用图标" min-width="80" align="center">
        <template slot-scope="scope">
          <div class="icon_img flex flex_cen">
            <img :src="scope.row.app_img" alt />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdSystemApp(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="getdeleteSystemApp(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination background :current-page.sync="listQuery.startSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加 -->
    <el-dialog :title="editSubjects ? '添加' : '编辑'" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="35%" @close="addFormclose">
      <el-form :model="addForm" :rules="rules" ref="ruleForm">
        <el-form-item label="应用名称:" label-width="130px" prop="packageName">
          <el-input class="add_select" v-model="addForm.packageName" placeholder="请输入应用名称"></el-input>
        </el-form-item>
        <el-form-item label="应用包名:" label-width="130px" prop="package">
          <el-input class="add_select" v-model="addForm.package" placeholder="请输入应用包名"></el-input>
        </el-form-item>
        <el-form-item label="专题图片" label-width="130px" prop="app_img">
          <el-upload class="avatar-uploader" action="#" :auto-upload="false" :show-file-list="false" :on-change="iconAvatarSuccess">
            <div v-if="addForm.app_img" style="height:148px;width:148px">
              <img :src="addForm.app_img" class="avatar" style="height:100%;width:100%" />
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon" style="height:148px;width:148px;line-height: 148px;background-color: #fbfdff;"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="getaddSystemApp('ruleForm')" size="mini" round>确 定</el-button>
        <el-button v-else type="primary" @click="geteditSystemApp('ruleForm')" size="mini" round>编辑</el-button>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryAllSystemApp, addSystemApp, queryIdSystemApp, editSystemApp, deleteSystemApp } from "@/api/allocation.js";
import { uploadPreviewImg } from "@/api/application";
import deleteDialog from "@/components/deleteDialog";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["应用名称", "应用包名", "应用图标", "创建时间"],
      key: 1,
      colData: [], //动态控制table
      total: 0,
      searchTable: "",
      select: "", //搜索条件
      //归属table
      browserTable: [],
      //添加按钮控制
      dialogFormVisible: false,
      subjectId: 0,
      //编辑按钮控制
      editSubjects: true,
      listQuery: {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
        type: 1,
        package: undefined,
        packageName: undefined
      },
      //添加表单  
      addForm: { package: "", packageName: "", app_img: "" },
      rules: {
        packageName: [{ required: true, message: "请输入应用包名", trigger: "blur" }],
        package: [{ required: true, message: "请输入应用名称", trigger: "blur" }],
        app_img: [{ required: true, message: "请上传图标", trigger: "blur" }]
      },
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryAllSystemApp()
  },
  methods: {
    //删除
    getdeleteSystemApp(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), id: this.deleteDialogs.deleteId }
      deleteSystemApp(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryAllSystemApp()
      })
    },
    //图片上传
    iconAvatarSuccess(res, file) {
      let fd = new FormData();
      fd.append('file', res.raw);
      fd.append('last_ip', sessionStorage.getItem("Ip"))
      fd.append('userId', localStorage.getItem("ID"))
      uploadPreviewImg(fd).then(res => {
        this.addForm.app_img = res.data.imgPath
      })
    },
    //修改包名信息
    geteditSystemApp(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addForm.id = this.subjectId
          editSystemApp(addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryAllSystemApp()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //ID查询包名详细信息
    getqueryIdSystemApp(id) {
      this.editSubjects = false
      this.subjectId = id
      queryIdSystemApp({ id: id }).then(res => {
        this.dialogFormVisible = true
        console.log('---编辑查询', res.data)
        this.addForm.package = res.data.package
        this.addForm.packageName = res.data.package_name
        this.addForm.app_img = res.data.app_img
      })
    },
    //添加包名
    getaddSystemApp(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addSystemApp(addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryAllSystemApp()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    getqueryAllSystemApp() {
      queryAllSystemApp(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      })
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    //搜索,1:package，2：packageName
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.type = 2
          this.listQuery.package = this.searchTable
          this.getqueryAllSystemApp();
          break;
        case '2':
          this.listQuery.type = 3
          this.listQuery.packageName = this.searchTable
          this.getqueryAllSystemApp();
          break;
      }
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryAllSystemApp();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryAllSystemApp();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1, package: undefined, packageName: undefined }
      this.getqueryAllSystemApp()
    },
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>